package com.u.finance.loans.service.impl;

import com.u.finance.loans.entity.Loans;
import com.u.finance.loans.entity.RepaymentSchedule;
import com.u.finance.loans.mapper.RepaymentScheduleMapper;
import com.u.finance.loans.service.IRepaymentScheduleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-03-31
 */
@Service
public class RepaymentScheduleServiceImpl extends ServiceImpl<RepaymentScheduleMapper, RepaymentSchedule> implements IRepaymentScheduleService {

    @Override
    public Boolean createSchedule(Loans loans) {
        // create schedule

        for (int i = 0; i < loans.getTotalMonth(); i++) {
            RepaymentSchedule repaymentSchedule = new RepaymentSchedule();
            repaymentSchedule.setLoanId(loans.getId());
            repaymentSchedule.setUserId(123L);
            repaymentSchedule.setDueDate(loans.getDueDate().toLocalDate().plusMonths(i + 1));
            repaymentSchedule.setPrincipal(loans.getAmount().divide(BigDecimal.valueOf(loans.getTotalMonth()), RoundingMode.HALF_UP));
            repaymentSchedule.setTotalAmount(repaymentSchedule.getPrincipal().add(loans.getAmount().multiply(loans.getAmount()).divide(BigDecimal.valueOf(100), RoundingMode.HALF_UP)));
            repaymentSchedule.setStatus("未还款");
            this.save(repaymentSchedule);
        }
        return true;
    }
}
